package com.coder.algorithm.offer_2;

/**
 * 把字符串转换成整数
 *
 * @author yuhushuan
 * @date 2020/7/4 22:24
 */
public class _67_1_StringToInt {
    private static Integer strToInt(String str) {
        if (str == null || str.length() == 0) {
            return null;
        }
        long number = 0;
        boolean minus = false;
        int index = 0;
        if (str.charAt(index) == '+') {
            index++;
        } else if (str.charAt(index) == '-') {
            minus = true;
            index++;
        }
        for (; index < str.length(); ++index) {
            char ch = str.charAt(index);
            if (ch >= '0' && ch <= '9') {
                number = number * 10 + (ch - '0');

                if ((!minus && number > 0x7fffffff) || (minus && number < 0x80000000)) {
                    number = 0;
                    break;
                }
            } else {
                number = 0;
                break;
            }
        }
        if (minus) {
            number = -number;
        }
        return (int) number;
    }


    public static void main(String[] args) {
        // 功能测试
        // 正数、负数、0
        print("12345");
        print("-12345");
        print("0");

        // 边界值测试
        print(Integer.toString(Integer.MIN_VALUE));
        print(Integer.toString(Integer.MAX_VALUE));

        // 特殊输入
        print(null);
        print("");
        print("123a222");
    }

    private static void print(String str){
        System.out.println("字符串：" + str);
        System.out.println("转成整数：" + strToInt(str) + '\n');

    }
}
